package com.lxblyw.web;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.google.gson.Gson;
import com.lxblyw.entity.Employee;
import com.lxblyw.entity.EmployeeProject;
import com.lxblyw.entity.Message;
import com.lxblyw.entity.MessageItem;
import com.lxblyw.entity.Project;
import com.lxblyw.service.MessageService;
import com.lxblyw.util.Const;
import com.lxblyw.util.DateUtil;
import com.lxblyw.util.PKUtil;

public class MessageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		String method = request.getParameter("_m");
		if(method == null || "".equals(method)) {
			list(request,response);
		} else if("save".equals(method)) {
			save(request,response);
		}
		
	}

	private void save(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Employee employee = (Employee) session.getAttribute(Const.EMPLOYEE_IN_SESSION);
		EmployeeProject ep = (EmployeeProject) session.getAttribute(Const.EMPLOYEEPROJECT_IN_SESSION);
		Project project = ep.getProject();
		
		String content = request.getParameter("content");
		System.out.println(content);
		content = new String(content.getBytes("ISO8859-1"),"UTF-8");
		System.out.println(content);
		
		
		Message msg = new Message();
		msg.setId(PKUtil.getPK());
		msg.setContent(content);
		msg.setCreatetime(DateUtil.getNow());
		msg.setEmployeeid(employee.getId());
		msg.setProjectid(project.getId());
		
		new MessageService().save(msg);
		Gson gson = new Gson();
		String json = gson.toJson(msg);
		response.setContentType("application/json;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();
	}

	private void list(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		EmployeeProject ep = (EmployeeProject) session.getAttribute(Const.EMPLOYEEPROJECT_IN_SESSION);
		Project project = ep.getProject();
		
		List<MessageItem> msgItemList = new MessageService().findByProjectId(project.getId());
		//System.out.println(msgList.size());
		
		Gson gson = new Gson();
		String json = gson.toJson(msgItemList);
		response.setContentType("application/json;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();
	}
}
